package com.xywy.bloodandroid.act;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.BaseHttpResponse;
import com.xywy.bloodandroid.bean.ImageUrl;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.FileUtil;
import com.xywy.bloodandroid.util.HttpClientUploadTask;
import com.xywy.bloodandroid.util.HttpClientUploadTask.HttpClientUploadResponse;
import com.xywy.bloodandroid.util.ImageUtil;
import com.xywy.bloodandroid.util.LogUtil;
import com.xywy.bloodandroid.util.NetUtil;
import com.xywy.bloodandroid.util.PhotoUtil;
import com.xywy.bloodandroid.util.ThreadPoolManager;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.widget.DialogItem;

/*******************************************
 * @Title: FreeAskQuestionAct.java
 * @Package com.xywy.tangandroid.activity
 * @Description: TODO(问医生问题)
 * @author smz
 * @date 2014-12-3 下午4:17:13
 * @version V1.0
 ********************************************/
public class FreeAskQuestionAct extends BaseActivity {
	protected static final int ASK_QUESSTION_SUCESS = 200;
	private RelativeLayout left_img;
	private TextView middle_title;
//	private TextView right_title;
	private LinearLayout tobar;
//	private ImageView right_img;
	private TextView online_question;
	private TextView man;
	private TextView female;
	private EditText age;
	private int flag;
	private int mark; // 100 是免费提问 200 电话
	private ImageView free_add_photo;

	private File takingPhoto;
	private String imagePath;
	private String outDirectory;// 压缩后的路径
	private HashMap<String, String> filepath;// 储存图片的路径
	// private List<ImageUrl> list;
	private List<String> list;// 暂时储存图片的地方
	private String Tag = "FreeAskQuestionAct";
	private int numimg = 0;// 记录上传图片的数量

	private String sex = "0";// 0是男 一是女

	// private List<String> list;
	private LinearLayout.LayoutParams params;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			UIUtil.DissDialog(context, waittingDialog);
			switch (msg.what) {
			case HttpClientUploadResponse.SUCESS:
				numimg++;
				String imgurl = (String) msg.obj;
				if (list.size() < 3 && list != null) {
					list.add(imgurl);
				}
				System.out.println("获取的图片的绝对路径....." + imgurl);
				// Intent intent = new Intent(context, QuestionSucessAct.class);
				// if (mark == 100)
				// intent.putExtra("mark", 100);
				// else if (mark == 200)
				// intent.putExtra("mark", 200);
				// startActivity(intent);
				// finish();//
				break;
			case HttpClientUploadResponse.FAIL:
				UIUtil.showToast(context, "上传失败");
				break;
			case HttpClientUploadResponse.ERROR:
				String error = (String) msg.obj;

				System.out.println("获取的返回的错误。。" + error);
				UIUtil.showToast(FreeAskQuestionAct.this, "提问失败");
				break;
			case ASK_QUESSTION_SUCESS:
				list.clear();
				Intent intent = new Intent(FreeAskQuestionAct.this,
						QuestionSucessAct.class);
				if (mark == 100)
					intent.putExtra("mark", 100);
				else if (mark == 200)
					intent.putExtra("mark", 200);
				startActivity(intent);
				finish();
				break;
			}
		}
	};

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_free_ask_question);
		mark = getIntent().getExtras().getInt("mark");

		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
//		right_title = (TextView) findViewById(R.id.right_title);
//		right_img = (ImageView) findViewById(R.id.right_img);

		feedbackContent = (EditText) findViewById(R.id.free_ask_queston_edit);
		edit_text_count = (TextView) findViewById(R.id.edit_text_count);

		free_add_photo = (ImageView) findViewById(R.id.free_ask_question_img);
		online_question = (TextView) findViewById(R.id.online_question);
		man = (TextView) findViewById(R.id.man);
		female = (TextView) findViewById(R.id.female);
		age = (EditText) findViewById(R.id.age);
		
		age.setInputType(InputType.TYPE_CLASS_PHONE);
		if (mark == 100 || mark == -100) {
			middle_title.setText("免费提问");
			online_question.setText("提交给医生");
		} else if (mark == 200) {
			middle_title.setText("电话医生");
			online_question.setText("提交申请单");
		}
		feedbackContent.addTextChangedListener(mTextWatcher);
		feedbackContent.setSelection(feedbackContent.length());

		int ss = (int) getResources().getDimension(R.dimen.ask_question_img);
		addImageLinear = (LinearLayout) findViewById(R.id.image_);
		params = new LinearLayout.LayoutParams(ss, ss);
		params.leftMargin = 10;
		params.gravity = Gravity.CENTER_VERTICAL;
		imageUrl = new ImageUrl();
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		free_add_photo.setOnClickListener(this);
		online_question.setOnClickListener(this);
		man.setOnClickListener(this);
		female.setOnClickListener(this);
		age.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		outDirectory = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ File.separator
				+ "xywy"
				+ File.separator
				+ "question";
		// list=new ArrayList<ImageUrl>();
		list = new ArrayList<String>();
		filepath = new HashMap<String, String>();
		flag = 0;
		clickColor(man, R.color.login_buttom_press, R.color.white_color);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			clearImage();// 清除压缩缓存
			finish();
			break;
		case R.id.free_ask_question_img:
			if (numimg < 3) {
				ArrayList<DialogItem> items = new ArrayList<DialogItem>();

				items.add(new DialogItem("拍照", R.layout.bottom_dialog_btn) {
					@Override
					public void onClick() {
						super.onClick();
						takingPhoto = PhotoUtil
								.getPhotoByTaking(FreeAskQuestionAct.this);
						LogUtil.i(Tag, "拍摄相片的路径。。。" + takingPhoto);
					}
				});
				items.add(new DialogItem("从相册中选择", R.layout.bottom_dialog_btn) {
					@Override
					public void onClick() {
						super.onClick();
						PhotoUtil.getPhotoFromAlbum(FreeAskQuestionAct.this);
					}
				});
				//
				items.add(new DialogItem("取消", R.layout.bottom_dialog_cancel));
				UIUtil.showBottomDialog(this, items);

			} else {
				UIUtil.showToast(context, "最多传3张相片哦");
			}
			break;
		case R.id.online_question:
			content = feedbackContent.getText().toString().trim();
			if (checkQuestionInfo()){
				if (mark == 100)
					sendQuestion();
				else if (mark == -100) {// 提交问题 给专家
					
//						sendExpertDoctor();
				}
			}
			// Intent intent = new Intent(this, QuestionSucessAct.class);
			// if (mark == 100)
			// intent.putExtra("mark", 100);
			// else if (mark == 200)
			// intent.putExtra("mark", 200);
			// startActivity(intent);
			// finish();//

			break;
		case R.id.man:
			sex = "0";
			clickColor(man, R.color.login_buttom_press, R.color.white_color
					);
			break;
		case R.id.female:
			sex = "1";
			clickColor(female, R.color.login_buttom_press, R.color.white_color);
			break;
		case R.id.age:
			// clickColor(age, R.color.login_buttom_press, R.color.text_color);
     
			

			break;

		default:
			break;
		}
	}

//	/**
//	 * 提交问题给医生
//	 */
//	private void sendExpertDoctor() {
//		String Title = feedbackContent.getText().toString().trim()
//				.substring(0, 9)
//				+ "...";
//		System.out.println("获取标题.." + Title.length());
//		PostRequest<String> request = new PostRequest<String>(
//				Constants.getSendToDoctorUrl("ask",context), String.class,
//				new OnVolleyResponseListener<String>() {
//
//					@Override
//					public void onError(VolleyError volleyError) {
//						UIUtil.DissDialog(context, waittingDialog);
//					}
//
//					@Override
//					public void onSuccess(String response) {
//						UIUtil.DissDialog(context, waittingDialog);
//						System.out.println("提交问题给专家的返回哦..." + response);
//						try {
//							JSONObject jsonObject = new JSONObject(response);
//							String mss = jsonObject.optString("msg");
//							String result = jsonObject.optString("result");
//							if ("1".equals(result)) {
//								UIUtil.showToast(context, mss);
//								list.clear();// 提问成功后 将数据全部清除
//								Intent intent = new Intent(
//										FreeAskQuestionAct.this,
//										QuestionSucessAct.class);
//								// 也用100的 各种信息即可
//								intent.putExtra("mark", 100);
//								startActivity(intent);
//								finish();
//							} else
//								UIUtil.showToast(context, mss);
//						} catch (JSONException e) {
//							e.printStackTrace();
//						}
//
//					}
//				});
//
//		HashMap<String, String> params1 = new HashMap<String, String>();
//		params1.put("detail", feedbackContent.getText().toString().trim());// 问题细节
//		params1.put("sex", sex);// 0男，1女
//		params1.put("age", age.getText().toString().trim());// 不能小于1
//		params1.put("uid", User.getIUserInstance(context).getUserid());//
//		params1.put("title", Title);// 问题标题
//		params1.put("sign", Constant.getKeyAndUid(context));// 问题标题
//		params1.put("fromurl", "app_tang");// 问题标题
//		request.setParams(params1);
//
//		if (list.size() > 0 && list.size() < 3) {
//			for (int i = 0; i < list.size(); i++) {
//				if (i == 0) {
//					params1.put("image", list.get(i));
//				} else {
//					params1.put("image" + i, list.get(i));
//				}
//			}
//		}
//		request.setIsParseJson(false);
//		executeRequest(request);
//
//	}

	/**
	 * 提交问题的借口
	 */
	private void sendQuestion() {
		String Title = feedbackContent.getText().toString().trim()
				.substring(0, 9)
				+ "...";
		PostRequest<BaseHttpResponse> request = new PostRequest<BaseHttpResponse>(
				Constants.getUrl("club", "Club_ask"), BaseHttpResponse.class,
				new OnVolleyResponseListener<BaseHttpResponse>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context, "你的网速有点慢~");
					}

					@Override
					public void onSuccess(BaseHttpResponse response) {
						UIUtil.DissDialog(context, waittingDialog);
						if (response.getState() == 200) {
							Message message = handler.obtainMessage();
							message.what = ASK_QUESSTION_SUCESS;
							handler.sendMessage(message);

						} else {
							UIUtil.showToast(context, response.getError());
						}

					}

				});
		HashMap<String, String> params1 = new HashMap<String, String>();
		params1.put("detail", feedbackContent.getText().toString().trim());// 问题细节
		params1.put("sex", sex);// 0男，1女
		params1.put("age", age.getText().toString().trim());// 不能小于1
		params1.put("userid", User.getInstance(context).getUserid());//
		params1.put("title", Title);// 问题标题
		params1.put("fromurl", "app_xuey");

		request.setParams(params1);

		if (list.size() > 0 && list.size() < 3) {
			for (int i = 0; i < list.size(); i++) {
				if (i == 0) {
					params1.put("image", list.get(i));
				} else {
					params1.put("image" + i, list.get(i));
				}
			}
		}
		// request.setIsParseJson(false);
		executeRequest(request);
	}

	private void clickColor(View view, int clickColor, int normalclcor) {
		if (view == man) {
			man.setBackgroundResource(clickColor);
			female.setBackgroundResource(normalclcor);

		}

		if (view == female) {

			man.setBackgroundResource(normalclcor);
			female.setBackgroundResource(clickColor);

		}

		if (view == age) {
			if (flag % 2 != 0) {
				flag++;
				age.setBackgroundResource(clickColor);
			} else {
				flag++;
				age.setBackgroundResource(normalclcor);
			}

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {

			case Constants.ALB_UM:// 相册
				if (data != null) {
					String photoPath = PhotoUtil.getPathByUri(this,
							data.getData());// 相片的路径
					Bitmap rigitBitmap = ImageUtil.loadRightDirectioniBitmap(
							ImageUtil.compressImageFromFile(photoPath),
							photoPath);
					System.out.println("photoPath --" + photoPath);
					imagePath = ImageUtil.compressBmpToFile(rigitBitmap, null);// 压缩图片
					System.out.println("lujing ---" + outDirectory);
					System.out.println("获取的相片的路径" + imagePath);

					AddImageView(rigitBitmap);
					sendimg(imagePath);
				}
				break;
			case Constants.PHOTO_GRAPH:// 拍照
				if (takingPhoto != null && takingPhoto.length() > 1024) {

					Bitmap rigitBitmap1 = ImageUtil.loadRightDirectioniBitmap(
							ImageUtil.compressImageFromFile(takingPhoto
									.getAbsolutePath()), takingPhoto
									.getAbsolutePath());// 相片方向矫正
					imagePath = ImageUtil.compressImage(
							takingPhoto.getAbsolutePath(), outDirectory, 500,
							500);
					System.out.println("获取相片的路径..." + imagePath);
					AddImageView(rigitBitmap1);
					sendimg(imagePath);
					break;
				}
			default:
				break;
			}
		}
	}

	private int max_length = 1000;
	private static final int MAX_COUNT = 500;

	private TextWatcher mTextWatcher = new TextWatcher() {
		private int editStart;
		private int editEnd;

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = feedbackContent.getSelectionStart();
			editEnd = feedbackContent.getSelectionEnd();
			feedbackContent.removeTextChangedListener(mTextWatcher);
			while (calculateLength(s.toString()) > MAX_COUNT) {
				s.delete(editStart - 1, editEnd);
				editStart--;
				editEnd--;
			}
			feedbackContent.addTextChangedListener(mTextWatcher);
			setLeftCount();
		}
	};
	private EditText feedbackContent;
	private TextView edit_text_count;
	private LinearLayout addImageLinear;
	private ImageUrl imageUrl;
	private String content;

	/**
	 * 
	 * @param c
	 * @return
	 */
	private long calculateLength(CharSequence c) {
		double len = 0;
		for (int i = 0; i < c.length(); i++) {
			int tmp = (int) c.charAt(i);
			if (tmp > 0 && tmp < 127) {
				len += 0.5;
			} else {
				len++;
			}
		}
		return Math.round(len);
	}

	/**
	 * 
	 */
	private void setLeftCount() {
		edit_text_count.setText(getInputCount() + "");
	}

	/**
	 * 
	 * 
	 * @return
	 */
	private long getInputCount() {
		return calculateLength(feedbackContent.getText().toString());
	}

	void AddImageView(Bitmap imgPath) {
		ImageView imageView = new ImageView(context);
		imageView.setImageBitmap(imgPath);
		imageView.setLayoutParams(params);
		addImageLinear.addView(imageView);
	}

	private void sendimg(String filth) {
		String url = Constants.getImageUrl();
		System.out.println("获取的链接" + url);
		if (NetUtil.hasNetwork(context)) {
			waitingDialog(context, "正在发送~");
			ThreadPoolManager.getInstance().executeTask(
					new HttpClientUploadTask(url, handler, filth, "submit"));
		} else {
			UIUtil.showToast(context, "请联网...");
			UIUtil.DissDialog(context, waittingDialog);
		}
	}

	/**
	 * 清空文件夹中压缩的图片
	 */
	private void clearImage() {
		FileUtil.deleteDirectory(outDirectory);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		clearImage();
	}

	private boolean checkQuestionInfo() {
		String content = feedbackContent.getText().toString().trim();

		String Age = age.getText().toString().trim();

		if (content.length() <= 0) {
			UIUtil.showToast(context, "问题描述不能为空");
			return false;
		}
		if (content.length() < 10) {
			UIUtil.showToast(context, "问题描述不能少于10个字");
			return false;
		}
		if (Age.length() <=0) {
			UIUtil.showToast(context, "年龄不能为空");
			return false;
		}
		if (Integer.valueOf(Age) == 0) {
			UIUtil.showToast(context, "年龄必须大于1岁~");
			return false;
		}

		return true;

	}
}
